<?php
namespace  Home\Biz;
use Home\Biz\AuthBiz;
class SaleBiz{
	
	
	
	
	public static function  addSaleDealerLog($log){
			
		M('sale_dealer_status_change_log')->add($log);	
	}
	
	
	
	
	
	
	
	
	public function  validateSale($sale,$option=1){
	
		if(empty($sale['sale_name'])){
			
			return '业务员用户名不能为空!';			
		}
		
		if(empty($sale['sale_real_name'])){
				
			return '业务员真实姓名不能为空!';
		}
		
		if($option == 1){
			
			if(empty($sale['password'])){
					
				return '密码选项不能为空!';
			}
			
		}
		
		if(empty($sale['sale_mobile'])){
				
			return '业务员电话不能为空!';

		}
		if(empty($sale['area_name'])){
				
			return '业务员所属大区不能为空!';
		}
		
		if(!empty($sale['email_address'])){
			
			if(!StringBiz::checkEmail($sale['email_address'])){
				return '业务员邮箱格式不正确!';
											
			}
	
		}
		
		
           return '';
	}
	
	
	
	public static function   addsale($sale_add_en){
		
		$error  = self::validateSale($sale_add_en);
		if(!empty($error)){
			
			return  $error;
		}
		

		$is_exist_name = M('whaley_user','','DB_whaley_system')->where("user_name='%s'",$sale_add_en['sale_name'])->find();
		if(!empty($is_exist_name)){
				
			return "业务员:".$sale_add_en['sale_name']."已存在!";
				
		}
		
		$is_exist_phone = M('whaley_user','','DB_whaley_system')->where("user_mobile='%s'",$sale_add_en['sale_mobile'])->find();
		
		if(!empty($is_exist_phone)){
			return "手机号:".$sale_add_en['sale_mobile']."已存在!";
		}
		if(!empty($sale_add_en['email_address'])){
			
			$is_exist_mail = M('sale_user')->where("email_address='%s'",$sale_add_en['email_address'])->find();
			if(!empty($is_exist_mail)){
			
				return "该邮箱已经被使用,请核对检查！";
			}
		}
		
			
			$whaley_user = array(
				'user_id'	=> $sale_add_en['sale_id'],
				'password' => md5(C('SystemConfig.encrypt_key').$sale_add_en['password']),
				'user_name' => $sale_add_en['sale_name'],
				'user_mobile' => $sale_add_en['sale_mobile'],
				'user_address' => $sale_add_en['sale_address'],
				'create_user'	=> "whaleyinfo.order SaleBiz.addSale",
				'create_date'	=> date("y-m-d H:i:s", time())
			);
		//先添加whaley_user 数据，然后添加业务员数据	
		M('whaley_user','','DB_whaley_system')->add($whaley_user);	
		M('sale_user')->add($sale_add_en);
		// 添加业务员默认页面登录权限
		
		if ($sale_add_en['sale_channel'] ==1){
		AuthBiz::addBussinessAuth($sale_add_en['sale_id']);
		}
		
		if($sale_add_en['sale_channel'] ==2){
		 AuthBiz::addVRBussinessAuth($sale_add_en['sale_id']);
		}
		
		if($sale_add_en['sale_channel'] ==3){
			AuthBiz::addSTBussinessAuth($sale_add_en['sale_id']);
		}
	
	}
	
	public  static function  updatesale($sale_add_en){
	
		$error  = self::validateSale($sale_add_en,2);
		if(!empty($error)){
				
			return  $error;
		}
		
		
		$is_exist_sale = M('sale_user')->where("sale_id='%s'",$sale_add_en['sale_id'])->find();
		
		if(empty($is_exist_sale)){
			return "业务员:".$is_exist_sale['sale_name']."不存在!";
					
		}
			
		
		$is_exist_name = M('whaley_user','','DB_whaley_system')->where("user_name='%s' and user_id !='%s'",$sale_add_en['sale_name'],$sale_add_en['sale_id'])->find();
		if(!empty($is_exist_name)){
				
			return "业务员:".$sale_add_en['sale_name']."已存在!";
				
		}
		
		$is_exist_phone = M('whaley_user','','DB_whaley_system')->where("user_mobile='%s' and user_id !='%s'",$sale_add_en['sale_mobile'],$sale_add_en['sale_id'])->find();
		
		if(!empty($is_exist_phone)){
			return "手机号:".$sale_add_en['sale_mobile']."已存在!";
		}
		
		if(!empty($sale_add_en['email_address'])){
			$is_exist_mail = M('sale_user')->where("email_address='%s' and sale_id !='%s'",$sale_add_en['email_address'],$sale_add_en['sale_id'])->find();
			if(!empty($is_exist_mail)){
			
				return "该邮箱已经被使用,请核对检查！";
			}
		}
		
		$whaley_user =array();
		
			if(empty($sale_add_en['password'])){
				
				$whaley_user = array(
						
						'user_name' => $sale_add_en['sale_name'],
						'user_mobile' => $sale_add_en['sale_mobile'],
						'user_address' => $sale_add_en['sale_address'],
						'update_user'	=> "whaleyinfo.order SaleBiz.updateSale",
						'update_date'	=> date("y-m-d H:i:s", time())
				);
				
			}
			
			else{
				
				
				$whaley_user = array(
						
						'password' => md5(C('SystemConfig.encrypt_key').$sale_add_en['password']),
						'user_name' => $sale_add_en['sale_name'],
						'user_mobile' => $sale_add_en['sale_mobile'],
						'user_address' => $sale_add_en['sale_address'],
						'update_user'	=> "whaleyinfo.order SaleBiz.updatesale",
						'update_date'	=> date("y-m-d H:i:s", time())
				);
			}
			//更新whaley_user
			M('whaley_user','','DB_whaley_system')->where("user_id='%s'",$sale_add_en['sale_id'])->save($whaley_user);
			
// 			echo M('','','DB_whaley_system')->getLastSql();
// 			return ;
			//更新sale_user
			M('sale_user')->where("sale_id='%s'",$sale_add_en['sale_id'])->save($sale_add_en);
				
		
		
		
	}
	
	
	public static function caculateTotalPage($totalCount, $pageSize)
	{
	
		$count = intval($totalCount / $pageSize);
	
		$countLeft = $totalCount % $pageSize;
	
		if ($countLeft != 0) {
			$count = $count + 1;
		}
	
		return $count;
	}
	
	
	
	
	public static function querySaleByPara($sale_id,$sale_name, $sale_mobile,$area_name,$department,$occupation,$sale_channel,$pageSize,$index ){
	
		if (!empty ($sale_name)) {
			$condition_array['sale_name'] = array('like', "%" . $sale_name . "%");
		}
	
		if (!empty ($sale_mobile)) {
			$condition_array['sale_mobile'] = array('like', "%" . $sale_mobile . "%");
		}
	
		if (!empty ($sale_id)) {
			$condition_array['sale_id'] = array('like',"%" . $sale_id . "%" );
		}
		
		if (!empty ($area_name)) {
			$condition_array['area_name'] = array('like', "%" . $area_name . "%");
		}
		if (!empty ($department)) {
			$condition_array['department'] = array('like', "%" . $department . "%");
		}
		if (!empty ($occupation)) {
			$condition_array['occupation'] = array('like', "%" . $occupation . "%");
		}
	
		if (!empty ($sale_channel)) {
			$condition_array['sale_channel'] = array('eq',$sale_channel );
		}
		
		//业务员登录查询逻辑，只能查询到自己
		$user_id = cookie ( 'login_user_id' );
		$sale_en = M ( 'sale_user' )->where ( "sale_name='%s'", $user_id )->find ();
		
		if (!empty($sale_en)){
			$sale_id_own=$sale_en['sale_id'];
			
			$condition_array['_string']= "sale_id ='$sale_id_own'";
		}
		
		$lst_sales = M('sale_user')->field()->where($condition_array)->page($index,$pageSize)->select();
	
	  
		// 总记录数
		$totalCount = M('sale_user')->where($condition_array)->count();
	
		// 总页数
		$totalPage = self::caculateTotalPage($totalCount, $pageSize);
		// 当前页记录数
		$currentCount = $lst_sales . $pageSize;
		// 下一页页码
		$nextIndex = $index + 1;
		// 上一页页码 如果是第一页，页码仍然为1
		$preIndex = 1;
		if ($index > 1) {
			$preIndex = $index - 1;
		}
	
		$resultMap = array(
				'totalCount' => $totalCount,
				'totalPage' => $totalPage,
				'currentPage' => $currentCount,
				'nextIndex' => $nextIndex,
				'preIndex' => $preIndex,
				'index' => $index,
				'datas' => $lst_sales
		);
	
	
		return $resultMap;
	
	}
	
	
	/**
	 * 
	 * @param unknown $sale_id 输入条件，根据该业务员ID,获取该业务员level。
	 * @param unknown $sale_name
	 * @param unknown $sale_mobile
	 * @param unknown $area_name
	 * @param unknown $department
	 * @param unknown $occupation
	 * @param unknown $sale_channel
	 * @param $type 1 查询上级 2 查询下级
	 * @param unknown $pageSize
	 * @param unknown $index
	 * @return unknown[]|string[]|number[]|mixed[]|boolean[]|NULL[]|object[]
	 */
	
	public static function querySaleByParaForSearch($sale_id,$sale_name, $sale_mobile,$area_name,$department,$occupation,$sale_channel,$type,$pageSize,$index ){
	
		
		
		//$sale_en=M('sale_user')->where("sale_id='%s'",$sale_id)->find();
		

		if (!empty ($sale_id)) {
			$condition_array['sale_id'] = array('like', "%" . $sale_id . "%");
		}
		
		if (!empty ($sale_name)) {
			$condition_array['sale_name'] = array('like', "%" . $sale_name . "%");
		}
	
		if (!empty ($sale_mobile)) {
			$condition_array['sale_mobile'] = array('like', "%" . $sale_mobile . "%");
		}
	
		
		if (!empty ($area_name)) {
			$condition_array['area_name'] = array('like', "%" . $area_name . "%");
		}
		if (!empty ($department)) {
			$condition_array['department'] = array('like', "%" . $department . "%");
		}
		if (!empty ($occupation)) {
			$condition_array['occupation'] = array('like', "%" . $occupation . "%");
		}
	
		if (!empty ($sale_channel)) {
			$condition_array['sale_channel'] = array('eq',$sale_channel );
		}
		
	
			//查询上级
			if($type==1){
			
				//$condition_array['sale_level'] = array('eq',$sale_en['sale_level']+100 );
			
			//查询下级	
			}else{
			//	$condition_array['sale_level'] = array('eq',$sale_en['sale_level']-100 );
				//排除已经分配的直接领导(即parent_sale_id 不为NULL)的业务员
				$condition_array['parent_sale_id']= array("exp"," IS  NULL");
			}
			
		
			
		
		$lst_sales = M('sale_user')->field()->where($condition_array)->page($index,$pageSize)->select();
	
		$sql=M()->getLastSql();
		 
		// 总记录数
		$totalCount = M('sale_user')->where($condition_array)->count();
	
		// 总页数
		$totalPage = self::caculateTotalPage($totalCount, $pageSize);
		// 当前页记录数
		$currentCount = $lst_sales . $pageSize;
		// 下一页页码
		$nextIndex = $index + 1;
		// 上一页页码 如果是第一页，页码仍然为1
		$preIndex = 1;
		if ($index > 1) {
			$preIndex = $index - 1;
		}
	
		$resultMap = array(
				'totalCount' => $totalCount,
				'totalPage' => $totalPage,
				'currentPage' => $currentCount,
				'nextIndex' => $nextIndex,
				'preIndex' => $preIndex,
				'index' => $index,
				'datas' => $lst_sales,
				'sql' =>$sql
		);
	
	
		return $resultMap;
	
	}
	
	
	
	
	public static function queryDealerWithoutRelationship($dealer_name, $dealer_type , $business_leader,$area_name, $sign_status,$status,$dealer_channel,$pageSize,$index){
		
		
		if (!empty ($dealer_name)) {
			$condition_array['dealer_name'] = array('like', "'%" . $dealer_name . "%'");
		}
		
		if (! empty ( $dealer_type )) {
			$condition_array['dealer_type'] = array('=', $dealer_type);
		}
		
		if (!empty ($business_leader)) {
			$condition_array['business_leader'] = array('like', "'%" . $business_leader . "%'");
		}
		
		if (!empty ($area_name)) {
			$condition_array['area_name'] = array('like', "'%" . $area_name . "%'");
		}
		
		if (! empty ( $sign_status )) {
			$condition_array['sign_status'] = array('=', $sign_status);
		}
		if (! empty ( $status )) {
			$condition_array['status'] = array('=', $status);
		}
		
		if (! empty ( $dealer_channel )) {
			$condition_array['dealer_channel'] = array('=', $dealer_channel);
		}
		$temp = array();
		$cn=0;
		if(sizeof($condition_array)>0){
			$temp[]=" AND ";
		}
		foreach ($condition_array as $key=>$val){

			$temp[] ="dealer_info.".$key.' ';
			$temp[] = join(" ", $val);
			if($cn != sizeof($condition_array)-1){
				$temp[]=" AND ";
			}
			$cn++;
		}

		$sql =  "dealer_id NOT IN ('')".join('',$temp);

		
		$lst_dealers = M('dealer_info')->where($sql)->page($index,$pageSize)->select();

		// 总记录数
		$totalCount = M('dealer_info')->where($sql)->count();
		
		// 总页数
		$totalPage = self::caculateTotalPage($totalCount, $pageSize);
		// 当前页记录数
		$currentCount = $lst_dealers . $pageSize;
		// 下一页页码
		$nextIndex = $index + 1;
		// 上一页页码 如果是第一页，页码仍然为1
		$preIndex = 1;
		if ($index > 1) {
			$preIndex = $index - 1;
		}
		
		$resultMap = array(
				'totalCount' => $totalCount,
				'totalPage' => $totalPage,
				'currentPage' => $currentCount,
				'nextIndex' => $nextIndex,
				'preIndex' => $preIndex,
				'index' => $index,
				'datas' => $lst_dealers
		);
		
		
		return $resultMap;
		
		
		
		
		
		
	}
	
	
	
	public static function  queryDealerBySaleAndPara($sale_id,$dealer_name, $dealer_type , $business_leader,$area_name, $sign_status,$status,$k3_code,$dealer_channel,$pageSize,$index){
		

		if (!empty ($dealer_name)) {
			$condition_array['dealer_name'] = array('like', "'%" . $dealer_name . "%'");
		}
		
		if (! empty ( $dealer_type )) {
			$condition_array['dealer_type'] = array('=', $dealer_type);
		}
		
		if (!empty ($business_leader)) {
			$condition_array['business_leader'] = array('like', "'%" . $business_leader . "%'");
		}
		
		if (!empty ($area_name)) {
			$condition_array['area_name'] = array('like', "'%" . $area_name . "%'");
		}
		
		if (! empty ( $sign_status )) {
			$condition_array['sign_status'] = array('=', $sign_status);
		}
		if (! empty ( $status )) {
			$condition_array['status'] = array('=', $status);
		}
		if (! empty ( $dealer_channel )) {
			$condition_array['dealer_channel'] = array('=', $dealer_channel);
		}
	    if (! empty ( $k3_code )) {
				
			if($k3_code == 1 ){
				//$condition_array ['k3_code'] = array (	'neq',	""	);
				$sql_k3 ="dealer_info.k3_code IS NOT  NULL  AND dealer_info.k3_code !='' AND dealer_info.k3_code != 'None'";
			}else {
				//$condition_array ['k3_code'] = array ('eq',	""	);

				$sql_k3 = "(dealer_info.k3_code IS NULL OR dealer_info.k3_code = 'None' OR dealer_info.k3_code = '')";
				//$condition_array['_query'] = "k3_codeISNULL&k3_code='None'&k3_code=&_logic=or";
			}
		}
		$temp = array();
		$cn=0;
		if(sizeof($condition_array)>0){
			$temp[]=" AND ";
		}
		foreach ($condition_array as $key=>$val){
				
			$temp[] ="dealer_info.".$key.' ';
			$temp[] = join(" ", $val);
			if($cn != sizeof($condition_array)-1){
				$temp[]=" AND ";
			}
			$cn++;
		}
			
		
				
		if(!empty($sql_k3))
		{
			$subsql = "".join("",$temp)." AND ".$sql_k3;
		}else{
			$subsql = "".join("",$temp);
		}
		
		
		/* 业务员单级关系语句
 		$sql =  "exists (SELECT	*  FROM sale_dealer_relationship AS sdr  WHERE dealer_info.dealer_id = sdr.dealer_id
          AND sdr.sale_id ='".$sale_id ."'".$subsql.")"; */
 		
 		//业务员多层关系
 		$sql =  "exists (SELECT	*  FROM sale_dealer_relationship AS sdr  WHERE dealer_info.dealer_id = sdr.dealer_id
          AND FIND_IN_SET(sdr.sale_id,getSubSaleList('".$sale_id ."')) ".$subsql.")";
       
 		
 		
 		
 		
 		
		
		$lst_dealers = M('dealer_info')->where($sql)->page($index,$pageSize)->select();

		// 总记录数
		
		
		
		$totalCount = M('dealer_info')->where($sql)->count();
		
	
		// 总页数
		$totalPage = self::caculateTotalPage($totalCount, $pageSize);
		// 当前页记录数
		$currentCount = $lst_dealers . $pageSize;
		// 下一页页码
		$nextIndex = $index + 1;
		// 上一页页码 如果是第一页，页码仍然为1
		$preIndex = 1;
		if ($index > 1) {
			$preIndex = $index - 1;
		}
		$resultMap = array(
				'totalCount' => $totalCount,
				'totalPage' => $totalPage,
				'currentPage' => $currentCount,
				'nextIndex' => $nextIndex,
				'preIndex' => $preIndex,
				'index' => $index,
				'datas' => $lst_dealers,
				
		);
		
		
		return $resultMap;
			
		
	}
	
	public static function  querySalePreAndSublevelRelationship($sale_id){
		
		$sale_en = M('sale_user')->where("sale_id='%s'",$sale_id)->find();
		$lst_pre_sales = M('sale_user')->where("sale_id='%s'",$sale_en['parent_sale_id'])->select();
		$lst_sub_sales = M('sale_user')->where("parent_sale_id='%s'",$sale_id)->select();
		$resultMap = array(
				
				'datas1' => $lst_pre_sales,
				'datas2' => $lst_sub_sales,
				'itself'=>$sale_id,
		
		);
		
		return $resultMap;
		
	}
	
	
	
	
	public static function queryDealerBySaleId($sale_id,$pageSize,$index ){
	

		$lst_dealers = M('dealer_info')->where("exists (SELECT	*  FROM sale_dealer_relationship AS sdr  WHERE dealer_info.dealer_id = sdr.dealer_id 
        AND sdr.sale_id ='%s' )",$sale_id)->page($index,$pageSize)->select();
	
		
		// 总记录数
		$totalCount = M('dealer_info')->where("EXISTS (SELECT	*  FROM sale_dealer_relationship AS sdr  WHERE dealer_info.dealer_id = sdr.dealer_id 
        AND sdr.sale_id ='%s' )",$sale_id)->count();
	
		// 总页数
		$totalPage = self::caculateTotalPage($totalCount, $pageSize);
		// 当前页记录数
		$currentCount = $lst_dealers . $pageSize;
		// 下一页页码
		$nextIndex = $index + 1;
		// 上一页页码 如果是第一页，页码仍然为1
		$preIndex = 1;
		if ($index > 1) {
			$preIndex = $index - 1;
		}
	
		$resultMap = array(
				'totalCount' => $totalCount,
				'totalPage' => $totalPage,
				'currentPage' => $currentCount,
				'nextIndex' => $nextIndex,
				'preIndex' => $preIndex,
				'index' => $index,
				'datas' => $lst_dealers
		);
	
	
		return $resultMap;
	
	}
	
	
	public static function queryDealerSaleRelationship($sale_id, $dealer_id){
		
		$res = M('sale_dealer_relationship')->where("sale_id='%s' and dealer_id='%s'",$sale_id,$dealer_id)->find();
		return $res;
		
	}
	
	public static  function addDealerSaleRelationship($sale_id, $dealer_id){
		
		$relation = array(
			'sale_id'	=>$sale_id,
			'dealer_id' => $dealer_id,
			'status' =>1,
				
		);
		
		M('sale_dealer_relationship')->add($relation);
		
		
		
		$log = array(
				'sale_id'	 => $sale_id,
				'dealer_id'  => $dealer_id,
				'operation'  =>'add',
				'operator_id' => cookie('login_user_id'),
				'create_user'	=> "whaleyinfo.order SaleBiz.addDealerSaleRelationship",
				'create_date'	=> date("y-m-d H:i:s", time())
		);
		
		SaleBiz::addSaleDealerLog($log);
		
		
	}
	
	
	public static  function delDealerSaleRelationship($sale_id, $dealer_id){
	 
		$sql = "delete from sale_dealer_relationship where sale_id='".$sale_id."' and dealer_id='".$dealer_id."'";
	   
		M()->execute($sql);
	   
		$log = array(
				'sale_id'	 => $sale_id,
				'dealer_id'  => $dealer_id,
				'operation'  =>'delete',
				'operator_id' => cookie('login_user_id'),
				'create_user'	=> "whaleyinfo.order SaleBiz.delDealerSaleRelationship",
				'create_date'	=> date("y-m-d H:i:s", time())
		);
		
		SaleBiz::addSaleDealerLog($log);
	  
	
	}
	
	
	
	public  static function delSaleRelationship($sale_id){
		

		$sql= "update sale_user set parent_sale_id=NULL where sale_id='".$sale_id."'";
	     return M()->execute($sql);
		
	}
	
	
	public  static function addPreSalelevel($sale_id,$parent_sale_id){
	
	
		$sql= "update sale_user set parent_sale_id='$parent_sale_id' where sale_id='".$sale_id."'";
		return M()->execute($sql);
	
	}
	
	public  static function addBatchSubSalelevel($sale_id_list,$parent_sale_id){
	
	
		$sql= "update sale_user set parent_sale_id='$parent_sale_id' where sale_id in ('".$sale_id_list."');";
		return M()->execute($sql);
	
	}
	
}